package cn.hh.pet.service.impl;

import cn.hh.basic.exception.BusinessException;
import cn.hh.basic.service.IBaiduAiAuditService;
import cn.hh.basic.util.*;
import cn.hh.order.domain.OrderPetAcquisition;
import cn.hh.order.mapper.OrderPetAcquisitionMapper;
import cn.hh.org.domain.Employee;
import cn.hh.org.domain.Shop;
import cn.hh.org.mapper.EmployeeMapper;
import cn.hh.org.mapper.ShopMapper;
import cn.hh.pet.domain.Pet;
import cn.hh.pet.domain.SearchMasterMsg;
import cn.hh.pet.domain.SearchMasterMsgAuditLog;
import cn.hh.pet.dto.MsgDto;
import cn.hh.pet.mapper.PetMapper;
import cn.hh.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.hh.pet.mapper.SearchMasterMsgMapper;
import cn.hh.pet.query.SearchMasterMsgQuery;
import cn.hh.pet.service.ISearchMasterMsgService;
import cn.hh.basic.service.impl.BaseServiceImpl;
import cn.hh.user.domain.Logininfo;
import cn.hh.user.domain.User;
import cn.hh.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IBaiduAiAuditService BaiduAiAuditService;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;


    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // 获取发布寻主消息的用户
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());

        // 1.添加寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        // 2.智能审核 - 审核 标题-名称-地址
        Boolean textBoo = BaiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName() + searchMasterMsg.getAddress());
        // 审核图片
        Boolean imageBoo = BaiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        if (textBoo && imageBoo){ // 通过
            // 2.1.审核通过: 修改寻主消息的状态为1 [审核通过,待处理] +  将当前寻主消息分配给最近的店铺 + 发送短信通知 + 添加审核日志
            // 设置状态和日志
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核通过");
            // 绑定店铺
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            // 50公里以内店铺
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null){ // 50公里以内找到店铺了,没有店铺就不用管
                searchMasterMsg.setShopId(nearestShop.getId());
                // 模拟发送短信或者邮件通知
                System.out.println("你有新的订单,请尽快处理" + searchMasterMsg.getTitle());
            }
            // 修改寻主消息对象
            searchMasterMsgMapper.update(searchMasterMsg);
            // 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            // audit_id - 自动审核,没有添加审核人
            log.setState(1); // 驳回
            log.setNote("审核通过!!!");
            // 保存审核日志
            searchMasterMsgAuditLogMapper.save(log);

        } else{ // 未通过
            // 2.2.审核失败:  修改寻主消息的状态为0 + 添加审核日志
            // 修改状态和日志
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("审核不通过!,原因: 有非法内容或图片!");
            // 修改寻主消息对象
            searchMasterMsgMapper.update(searchMasterMsg);

            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            // audit_id - 自动审核,没有添加审核人
            log.setState(0); // 驳回
            log.setNote("审核不通过!,原因: 有非法内容或图片!");
            // 保存审核日志
            searchMasterMsgAuditLogMapper.save(log);
            // 抛异常
            throw new BusinessException("审核不通过!,原因: 有非法内容或图片!");

        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        // 如果当前管理员是店铺管理员: 要设置shopId
        // 如果当前管理员是平台管理员: 不设置shopId
        if (employee.getShop_id() != null){ // 店铺管理员
            query.setShopId(employee.getShop_id());
        }

        return super.queryPage(query);
    }

    /**
     *  拒单
     * @param msgId
     */
    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    /**
     * 接单
     * @param msgDto
     */
    @Override
    public void accept(MsgDto msgDto) {
        Long empId = msgDto.getHandler();  // 收购人
        Long msgId = msgDto.getMsgId(); // 宠物
        String note = msgDto.getNote(); // 日志

        // 校验: 当前寻主消息是否已经被接单了
        OrderPetAcquisition orderTem = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (orderTem != null){ // 查到了正在被处理的订单
            throw new BusinessException("订单正在处理......请耐心等待");
        }



        // 1.创建宠物对象
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2pet(searchMasterMsg);
        petMapper.save(pet);

        // 2.创建收购单
        OrderPetAcquisition order = buildOrder(pet,searchMasterMsg,empId);
        orderPetAcquisitionMapper.save(order);

        // 3.发短信或邮件告诉收购人在规定时间之内去收购宠物
        System.out.println("你有新的订单! 请在规定时间内去处理");

    }

    private OrderPetAcquisition buildOrder(Pet pet, SearchMasterMsg msg, Long empId) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        // 使用生成订单号的工具类传入用户id,获取到订单编号对象
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        // 设置订单编号
        order.setOrderSn(orderSn);
        order.setDigest(msg.getTitle());
        // 获取当前系统时间(毫秒数) + 两天的时间  [两天之后的此刻就是最后的收购时间,否则就通过定时器取消订单]
        long timeTem = System.currentTimeMillis() + 2*24*60*60*1000;
        order.setLastcomfirmtime(new Date(timeTem));
        order.setState(0); // 待处理
        order.setPrice(msg.getPrice());
        // paytype : 支付方式,在处理订单时才处理
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());

        return order;
    }

    private Pet searchMasterMsg2pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;

    }


}
